import requests
import json


def search_products(search_key, sort=0, page_num=1, page_size=10):
    """
    搜索Zen-Bio网站上的商品

    Args:
        search_key (str): 搜索关键词
        sort (int): 排序方式，0表示默认排序
        page_num (int): 页码
        page_size (int): 每页显示数量

    Returns:
        dict: 搜索结果的JSON数据
    """
    headers = {
        "Accept": "*/*",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Cache-Control": "no-cache",
        "Connection": "keep-alive",
        "Content-Type": "application/json",
        "Origin": "https://www.zen-bio.cn",
        "Pragma": "no-cache",
        "Referer": f"https://www.zen-bio.cn/goods?searchKey={requests.utils.quote(search_key)}&sort={sort}&pageNum={page_num}&pageSize={page_size}",
        "Sec-Fetch-Dest": "empty",
        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Site": "same-origin",
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36",
        "Wmeimob-Language": "cn",
        "sec-ch-ua": '"Not)A;Brand";v="8", "Chromium";v="138", "Google Chrome";v="138"',
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": '"macOS"',
    }

    url = "https://www.zen-bio.cn/web/api/product"
    data = {
        "searchKey": search_key,
        "sort": sort,
        "pageNum": page_num,
        "pageSize": page_size,
        "customFields": [],
    }

    try:
        # 发送请求
        response = requests.post(
            url, headers=headers, data=json.dumps(data, separators=(",", ":"))
        )
        response.raise_for_status()  # 检查请求是否成功

        # 解析并返回结果
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"请求出错: {e}")
        return None


def get_product_detail(product_no):
    """
    获取指定产品编号的详细信息

    参数:
        product_no (str): 产品编号

    返回:
        dict: 产品详情的JSON数据
    """
    import requests
    import json

    url = f"https://www.zen-bio.cn/web/api/product/{product_no}"
    headers = {
        "Accept": "*/*",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Cache-Control": "no-cache",
        "Connection": "keep-alive",
        "Content-Type": "application/json",
        "Pragma": "no-cache",
        "Referer": f"https://www.zen-bio.cn/goodsDetail?productNo={product_no}&pageNum=1&pageSize=5",
        "Sec-Fetch-Dest": "empty",
        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Site": "same-origin",
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36",
        "Wmeimob-Language": "cn",
        "sec-ch-ua": '"Not)A;Brand";v="8", "Chromium";v="138", "Google Chrome";v="138"',
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": '"macOS"',
    }
    # 注意：如果需要登录态，可以在此处设置 cookies
    # cookies = {"JSESSIONID": "xMa_1S5p5ELQydvoo0rGZnq8Dfv6woHRUH5UhIw6"}
    cookies = {}

    try:
        response = requests.get(url, headers=headers, cookies=cookies)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"请求出错: {e}")
        return None


def gen_custom_fields_table(custom_field_list: list) -> str:
    """
    将 customFieldList 转为带样式的 HTML 表格，提升可读性。
    :param custom_field_list: List[dict]，每个 dict 至少包含 productFieldsName 和 content
    :return: str，HTML 表格字符串
    """
    style = """<style>table.custom-fields-table{border-collapse:separate;border-spacing:0;width:100%;max-width:100%;font-size:15px;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Arial,sans-serif;box-shadow:0 4px 8px rgba(0,0,0,0.1);border-radius:8px;overflow:hidden;margin:20px 0}table.custom-fields-table th,table.custom-fields-table td{padding:12px 15px;text-align:left;vertical-align:middle;line-height:1.5}table.custom-fields-table th{background-color:#4a86e8;color:white;font-weight:600;text-transform:uppercase;font-size:14px;letter-spacing:0.5px;border-top:none;position:relative}table.custom-fields-table th:first-child{width:180px}table.custom-fields-table td{border-bottom:1px solid#e0e0e0;border-right:1px solid#e0e0e0;transition:background-color 0.2s ease}table.custom-fields-table td:first-child{border-left:1px solid#e0e0e0;background-color:#f5f7fa;font-weight:500;color:#333}table.custom-fields-table tr:last-child td{border-bottom:1px solid#e0e0e0}table.custom-fields-table tr:nth-child(even){background-color:#f9f9f9}table.custom-fields-table tr:hover td{background-color:#edf3ff}@media screen and(max-width:600px){table.custom-fields-table{font-size:14px;box-shadow:0 2px 4px rgba(0,0,0,0.1)}table.custom-fields-table th,table.custom-fields-table td{padding:10px}table.custom-fields-table th:first-child{width:120px}}</style>"""
    table = [
        style,
        '<table class="custom-fields-table">',
        "<thead><tr><th>名称</th><th>内容</th></tr></thead>",
        "<tbody>",
    ]
    for field in custom_field_list:
        name = field.get("productFieldsName", "")
        content = field.get("content", "")
        table.append(f"<tr><td>{name}</td><td>{content}</td></tr>")
    table.append("</tbody></table>")
    return "\n".join(table)


def combine_detail(json_data: dict) -> str:
    """
    将产品详情和自定义字段表格合并
    :param json_data: dict，产品详情JSON数据
    :return: str，合并后的HTML字符串
    """
    data_list = []
    data_list.append(
        {
            "productFieldsName": "产品名称",
            "content": json_data["name"],
        }
    )
    data_list.append(
        {"productFieldsName": "稀释倍率", "content": json_data["dilutionRatio"]}
    )
    data_list.extend(json_data["customFieldList"])
    return gen_custom_fields_table(data_list)


def process_data(proname: str) -> tuple[str, list] | None:
    """获取商品详情和图片列表"""
    _search = search_products(proname)
    if _search["data"]["total"] == 0:
        return None, None
    # 获取图片列表
    _img_list = [
        item["imgUrl"] for item in _search["data"]["list"][0]["productImageList"]
    ]
    # 获取产品详情
    _product_no = _search["data"]["list"][0]["productNo"]
    _detail = get_product_detail(_product_no)["data"]
    # 合并产品详情和自定义字段表格
    return combine_detail(_detail), _img_list


# 使用示例
if __name__ == "__main__":
    # results = search_products("Phospho-Histone H2A.X (Ser139) (7G9) Mouse mAb抗体")
    print(process_data("PI3 Kinase p85 alpha (1C8) Mouse mAb一抗"))
